package basicprotocol;

import java.io.*;
import java.net.*;

public class SimpleMessage implements Serializable {

    public SimpleMessage(int command, String id, Serializable message) {
        this.command = command;
        this.id = id;
        this.message = message;
    }

    public SimpleMessage(int command) {
        this(command, null, null);
    }

    public SimpleMessage() {
        this(BasicProtocol.ACK_MSG, null, null);
    }

    public void send(Socket socket) throws IOException {
        ObjectOutputStream out =
                new ObjectOutputStream(socket.getOutputStream());
        out.writeObject(this);
        // out.close();
    }

    public static SimpleMessage receive(Socket socket)
            throws IOException, ClassNotFoundException {
        ObjectInputStream in =
                new ObjectInputStream(socket.getInputStream());
        SimpleMessage result = (SimpleMessage) in.readObject();
        // in.close();
        return result;
    }

    // <editor-fold defaultstate="collapsed" desc="get' s set' s"> 
    public int getCommand() {
        return command;
    }

    public void setCommand(int command) {
        this.command = command;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public Serializable getMessage() {
        return message;
    }

    public void setMessage(Serializable message) {
        this.message = message;
    }
    // </editor-fold> 

    @Override
    public String toString() {
        return String.format("(%s, %s, %s)",
                BasicProtocol.getDescription(command),
                ((id != null) ? id : "<indefinido>"),
                ((message != null) ? message.toString() : "<null>"));
    }
    private int command;
    private String id;
    private Serializable message;
}
